package com.xgluo;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author xgluo
 * @program: makePackage
 * @name: CopyFiles
 * @description: 将指定路径下的文件和编译后的文件输出到，path文件所在目录
 * @date 2025年02月27日
 */
public class CopyFiles {
    
    // 获取源文件的所在项目的基础路径
    private String projectDir;
    private String classDir;
    private String webContextDir;
    
    public CopyFiles() {
        ReadConfigFile instance = ReadConfigFile.getInstance();
        if(instance == null){
            RuntimeException runtimeException = new RuntimeException("未配制项目路径，请先完善配制文件");
            runtimeException.printStackTrace();
            return;
        }
        projectDir = instance.getProjectPath();
        classDir = instance.getClassPath();
        webContextDir = instance.getWebcontextPath();
    }

    /**
     * 根据路径创建文件到指定目录，目录不存在则创建
     * @param filePath 文件路径
     */
    public void copyFiles(String filePath) {

        Path pathSour = Paths.get(filePath);
        String destFilePath = getDestPath(filePath);
        Path pathDest = Paths.get(destFilePath);
        Path parentDir = pathDest.getParent();
        try {
            // 如果父目录不存在则创建
            if (parentDir != null && !Files.exists(parentDir)) {
                Files.createDirectories(parentDir);
            }

            // 创建文件
            Files.copy(Paths.get(projectDir + filePath), Paths.get(destFilePath));
            if(filePath.endsWith(".java")){
                File[] classFileList = getClassFileList(filePath);
                for (int i = 0; i < classFileList.length; i++) {
                    Files.copy(classFileList[i].toPath(), Paths.get(parentDir+"/"+classFileList[i].getName()));
                }
            }
            System.out.println("文件创建成功：" + pathDest);
        } catch (IOException e) {
            System.err.println("文件创建失败：" + e.getMessage());
        }
    }

    /**
     * @description: 根据源文件路径生成目标文件路径
     * @param filePath
     * @return destFilePath
     * @date 2025/3/4
     * @author xgluo
     */
    private String getDestPath(String filePath) {
       if(filePath == null || "".equals(filePath)) {
           return "";
       }
       String destParentPath = projectDir+"/"+"result"+"/";
       // 对src 和webcontext 需去除第一目录
       int i = 0;
       if(filePath.startsWith(PathConstant.JAVA_PREFFIX)){
           i = filePath.indexOf("/", 1);
           return destParentPath+filePath.substring(i+1, filePath.length());
       }else if(filePath.startsWith(PathConstant.WEB_SUFFIX)){
           i = filePath.indexOf("/", 1);
       }
        return destParentPath+filePath.substring(i+1, filePath.length());
    }

    /**
     * @description: java文件需要额外生成class文件名
     * @param filePath
     * @return destFilePath
     * @date 2025/3/4
     * @author xgluo
     */
    public File[] getClassFileList(String filePath) {
        // 获取父目录
        int i = 0;
        if(filePath.startsWith(PathConstant.JAVA_PREFFIX)){
            i = filePath.indexOf("/", 1);
            filePath = projectDir+classDir+"/"+filePath.substring(i+1, filePath.length()).replaceAll(".java",".class");
        }else{
            System.out.println(filePath);
        }
        Path pathSour = Paths.get(filePath);
        String fileName = pathSour.getFileName().toString();
        Path pathSourParent = pathSour.getParent();
        File file = new File(pathSourParent.toString());
        File[] files = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File pathname, String name) {
                if(fileName.equals(name)){
                    return true;
                }else{
                    return name.contains(fileName.substring(0,fileName.indexOf(".")) + "$");
                }
            }
        });

        return files;
    }

}
